<template>
  <div v-loading="detailLoading" :class="{'mobile-create mobile-small-padding': showMobilePage}" class="create-original-wrap">
    <div class="original-info">
      <explanation :explanation="explanationObj" class="explanation"/>
      <Title title="基本信息" font-size="16px" style="margin: 0 0 10px" class="title"/>
      <el-form ref="originalForm" :rules="rules" :model="originalInfo" :label-position="showMobilePage?'left':'right'" :class="{'mobile-el-form': showMobilePage}" class="original-form" label-width="110px">
        <el-row type="flex">
          <el-col>
            <el-form-item label="创建人：" class="no-required">
              <ToolTip :content="originalInfo.createUser" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="所属部门：" class="no-required">
              <ToolTip :content="originalInfo.departmentName" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="职位：" class="no-required">
              <ToolTip :content="originalInfo.post" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="申请说明" prop="describe" class="decribe">
              <el-input v-model="originalInfo.describe" type="textarea" name="remark" maxlength="200" placeholder="请输入申请查看合同扫描件的原因" resize="none"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="pdfSetting" class="radios" label="水印要求">
              <el-tooltip :open-delay="300" placement="top" effect="dark">
                <div slot="content">
                  <div>设置PDF原件展示水印的内容</div>
                  <div>{{ `个人：水印展示“厦门飞博共创网络科技股份有限公司 ${userInfo.jobNumber}${userInfo.userName}”` }}</div>
                  <div>公司：水印展示“厦门飞博共创网络科技股份有限公司” </div>
                  <div>无水印：不展示水印</div>
                </div>
                <tipIcon class="tip-icon" is-diy/>
              </el-tooltip>
              <el-radio-group v-model="originalInfo.pdfSetting">
                <el-radio :label="0">个人</el-radio>
                <el-radio :label="1">公司</el-radio>
                <el-radio :label="2">无水印</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="relation-legal">
        <div class="relation-header">
          <Title title="合同列表" font-size="16px"/>
          <PlainCreateBtn
            size="small"
            @click="relatedContractShow">选择合同</PlainCreateBtn>
        </div>
        <contractList
          ref="contractList"
          :is-create="true"
          :contract-list="contractList"
          @delContract="delContract"
          @update="update"
        />
      </div>
    </div>
    <!-- 2.9.7修改成弹窗，修改时流程可以被编辑 -->
    <audit-process
      ref="auditProcess"
      v-model="auditInfo"
      :loading="loading"
      :old-audit-info="oldAuditInfo"
      :flow-structure="processDetail"

      :is-modify="Boolean(remodifyId)"
      :disable="Boolean(remodifyId)"
      :is-modify-form="Number(isModifyForm)"
      :current-process-index="Number(currentProcessIndex)"
      @submit="submit"
      @getProcess="getProcess"
    />
    <fixed-pagination>
      <div class="center">
        <el-button v-if="(!reapplyId && !remodifyId) || createNew" type="info" size="small" class="back-btn empty-btn-style" @click="saveDraft">保存草稿</el-button>
        <el-button type="primary" size="small" class="submit-btn" @click="openDrawer">发起审批</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">返回</el-button>
      </div>
    </fixed-pagination>
    <!-- 合同弹窗 -->
    <relatedContract
      ref="relatedContract"
      :visible.sync="showRelatedContract"
      :has-contract-code="true"
      :confirm-text="'确认选择'"
      :is-show-other="true"
      multiple
      @updateItem="updateItem"
      @confirmRelatedContract="confirmRelatedContract"
    />
  </div>
</template>
<script>
import Title from '@/components/Title';
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import relatedContract from '@/components/CreateOrder/relatedContract';
import contractList from '../components/contractList';
import { showModal } from '@/utils/message';
import { createAuditStructure } from '@/utils/aduitor';
import { mapState } from 'vuex';
import { isContained } from '@/utils/tools';
import processCreate from '@/mixins/processCreate';
import mobileCreate from '@/mixins/mobileCreate';
// api
import { originalCreate, originalEdit, originalInfo, formSubmit } from '@/api/original';
import { processManagementDetail } from '@/api/legal';
export default {
  components: { Title, AuditProcess, explanation, relatedContract, contractList },
  mixins: [processCreate, mobileCreate],
  data() {
    return {
      antiShakeTime: 0, // 防抖时间
      originalId: '', // 精力分配标识符
      originalInfo: {// 基本信息
        createUser: '',
        departmentName: '',
        post: '',
        creatorId: '',
        describe: '',
        contractIds: [],
        pdfSetting: 0
      },
      contractList: [],
      remodifyId: null, // 审批修改
      reapplyId: null, // 重新申请
      processDetail: null,
      auditInfo: {// 流程信息
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      },
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      rules: {
        describe: [{ required: true, trigger: 'blur', validator: this.validate('请输入申请查看合同扫描件的原因') }],
        pdfSetting: [{ required: true, trigger: 'change', validator: this.validate('请选择') }]
      },
      loading: false,
      detailLoading: false,
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      showRelatedContract: false
    };
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'originalDetail') {
      to.meta.isDetail = true;
    } else {
      to.meta.isDetail = false;
    }
    next();
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    processStructure() {
      if (!this.processDetail) return [];
      return this.processDetail.process;
    }
  },
  created() {
    this.originalId = Number(this.$route.query.originalId) || '';
    this.createNew = Number(this.$route.query.createNew) || 0;
    this.reapplyId = this.$route.query.reapplyId || null;
    this.remodifyId = this.$route.query.remodifyId || null;
    if (this.originalId) {
      this.getOriginalInfo();
      this.reapplyId && this.getExplanation();
    } else {
      this.initCreate();
      this.getExplanation();
    }
  },
  methods: {
    initCreate() {
      const { userName, currentDepartment, post, id } = this.userInfo;
      this.originalInfo.createUser = userName || '';
      this.originalInfo.creatorId = id || '';
      this.originalInfo.departmentName = currentDepartment && currentDepartment.length > 0 ? currentDepartment[0].name : '';
      this.originalInfo.post = post || '';
    },
    // 合同关联
    confirmRelatedContract(data) {
      this.showRelatedContract = false;
      this.contractList = data;
    },
    update(id) {
      this.$refs.relatedContract.update(id);
    },
    updateItem(item) {
      this.$refs['contractList'].updateItem(item);
    },
    delContract(idx) {
      this.contractList.splice(idx, 1);
    },
    validate(msg) {
      return (rule, value, callback) => {
        if (!value && value !== 0) { callback(new Error(msg)); } else { callback(); }
      };
    },
    // 打开弹窗
    relatedContractShow() {
      this.showRelatedContract = true;
      this.$refs['relatedContract'].init();
      this.$refs['relatedContract'].initSelectData(this.contractList);
    },
    // 信息获取
    getOriginalInfo() {
      this.detailLoading = true;
      originalInfo(this.originalId).then(res => {
        if (res.code !== 200) { this.$message.error(res.message); }
        const { createUser, departmentName, post, describe, contractList, creatorId, pdfSetting } = res.data;
        this.originalInfo = {
          createUser,
          departmentName,
          post,
          creatorId,
          describe,
          pdfSetting
        };
        if (this.createNew) { this.initCreate(); }
        this.originalInfo.contractId = contractList ? contractList.map(el => el.id) : [];
        this.contractList = contractList || [];
        if (res.data.auditInfo && !this.reapplyId) {
          this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
          this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
          this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
        } else {
          this.getExplanation();
        }
        this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        this.detailLoading = false;
      }).catch(err => {
        this.detailLoading = false;
        console.log(err);
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const data = {
        originalInfo: this.originalInfo,
        type: 14
      };
      data.originalInfo.contractIds = this.contractList.map(el => el.id);
      formSubmit(data).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            // 创建人回填
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, this.userInfo);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      if (!isContained(nowProcessIds, oldProcessIds)) {
        return true;
      }
      return false;
    },
    getExplanation() { // 获取审批说明
      processManagementDetail({ id: 3527, type: 14 }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    saveDraft() {
      if (!this.originalId || this.createNew) {
        this.originalCreate(1, '保存草稿成功');// 1为保存草稿
      } else {
        this.originalEdit(1);
      }
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    openDrawer() { // 2.9.7 流程弹窗
      this.$refs['originalForm'].validate(valid => {
        if (valid) { // 表单校验通过，则仅提交表单部分，不提交流程信息，用来获取最新流程
          if (!this.contractList || this.contractList.length === 0) {
            this.$message.warning('请选择要申请原件的合同');
            return;
          }
          this.getProcessDetail();
        }
      });
    },
    submit(senders = []) {
      this.modifySenders = senders;// 存到mixins
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.originalEdit(2);
        return;
      }
      showModal('提交申请后无法进行修改?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        if (!this.originalId || this.reapplyId) { // 重新提交也是新建
          this.originalCreate(2, '新建申请原件成功');
        } else {
          this.originalEdit(2);
        }
      }).catch(() => {
        return false;
      });
    },
    originalEdit(submitType) { // 1草稿编辑 2为详情编辑
      const data = Object.assign({}, this.originalInfo);
      data.isEditAudit = false;
      data.contractIds = this.contractList ? this.contractList.map(el => el.id) : [];
      data.auditInfo = JSON.parse(JSON.stringify(this.auditInfo));
      data.submitType = submitType;
      if (this.remodifyId && this.isRefresh) {
        data.isEditAudit = true;// 修改时，流程被编辑或者更新
      }
      this.handleModifyData(data);
      originalEdit(this.originalId, data).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
        }
        if (res.data.id && res.data.processId) {
          this.$router.push({
            name: 'originalDetail',
            query: {
              originalId: res.data.id,
              processId: res.data.processId
            }
          });
        } else {
          this.$router.push({
            name: 'original'
          });
        }
      }).catch(err => {
        if (err.code === 502 && !this.remodifyId) { // 503 表示流程状态已变更
          this.$refs['auditProcess'].setShowRefresh(true);
          console.log(err);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({
            routeName: 'originalDetail',
            params: {},
            query: {
              originalId: this.originalId,
              processId: this.remodifyId
            }
          });
        }
      });
    },
    originalCreate(submitType, message) { // 1草稿 2为保存提交 3重新申请
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      const data = Object.assign({}, this.originalInfo);
      data.isEditAudit = false;
      data.contractIds = this.contractList.map(el => el.id);
      data.auditInfo = JSON.parse(JSON.stringify(this.auditInfo));
      data.submitType = submitType;
      if (this.reapplyId && !this.createNew) {
        data.submitType = 3;
        this.originalId = null;
        // data.byReapplyId = this.originalId;//精力分配无关联信息，暂不传原id
      }
      originalCreate(data).then(res => {
        if (res.code !== 200) { this.$message.error(res.message); return; }
        this.$message.success(message);
        if (submitType === 2) {
          this.$router.push({
            name: 'originalDetail',
            query: {
              originalId: res.data.id,
              processId: res.data.processId
            }
          });
          return;
        } else {
          this.$router.push({
            name: 'original'
          });
        }
      }).catch(err => {
        if (err.code === 502 && !this.remodifyId) {
          this.$refs['auditProcess'].setShowRefresh(true);
          console.log(err);
        }
      });
    },
    toBack() {
      if (this.remodifyId) {
        this.processId = this.remodifyId;
      }
      if (this.reapplyId) {
        this.processId = this.reapplyId;
      }
      if (this.$route.meta.isDetail) {
        this.$router.push({
          name: 'originalDetail',
          query: {
            originalId: this.originalId,
            processId: this.processId
          }
        });
        return;
      }
      this.$router.push({
        name: 'original'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
	.create-original-wrap{
		padding: 20px 24px 56px;
		margin: 16px;
		background: #FFFFFF;
		min-height: calc(100vh - 56px);
    .tip-icon {
      position: absolute;
      left: -96px;
      top: 50%;
      transform: translateY(-50%);
    }
    .empty-btn-style {
      border-color: #406EFF;
      background: #fff;
      color: #406EFF;
      width: 80px;
      padding: 7px 0;
      text-align: center;
    }
    .original-form{
      &::v-deep {
        .el-row:first-of-type {
          margin-bottom: 24px;
          .el-col, .el-form-item {
            height: 24px;
          }
        }
        .el-row:last-of-type {
          .el-col:last-of-type {
            height: 24px;
            .el-form-item {
              height: 24px;
            }
          }
        }
        .el-form-item__label{
          color: #999999;
        }
        .el-form-item {
          margin-bottom: 0;
          .el-radio__label {
            font-size: 14px;
            padding-left: 6px;
          }
        }
      }
      .decribe{
          &::v-deep .el-form-item__label{
          color: #666666;
        }
      }
    }
    .relation-legal{
      margin-top: 32px;
    }
    .explanation{
      padding-left: 9px;
    }
    &::v-deep {
      .el-textarea .el-textarea__inner{
        width: 80%;
        height: 100px;
      }
    }
    .relation-header{
      display: flex;
      align-items: center;
      margin-bottom: 12px;
    }
    .radios{
      position: relative;
      &::v-deep{
        .el-radio {
          font-size: 14px;
          margin-right: 12px!important;
        }
        .el-radio:last-child {
          margin-right: 4px!important;
        }
      }
    }
	}
  .mobile-create {
    .original-form{
      &::v-deep {
        .el-row:first-of-type {
          margin-bottom: 0px;
        }
      }
    }
    .title {
      margin-bottom: 4px !important;
    }
    .tip-icon {
      left: -38px;
    }
    .el-col {
      margin-bottom: 12px;
    }
    .el-row {
      display: block;
    }
  }
</style>
